package com.mao.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mao.common.BaseContext;
import com.mao.entity.AddressBook;
import com.mao.mapper.AddressBookMapper;
import com.mao.service.AddressBookService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements AddressBookService {

    /**
     * 查询所有的地址簿
     * @param addressBook
     * @return
     */
    @Override
    public List<AddressBook> listAddressBook(AddressBook addressBook) {
        LambdaQueryWrapper<AddressBook> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressBook::getIsDeleted,"0");
        queryWrapper.eq(addressBook.getUserId()!=null,AddressBook::getUserId,addressBook.getUserId());
        queryWrapper.orderByDesc(AddressBook::getUpdateTime);
        List<AddressBook> addressBookList = this.list(queryWrapper);
        return addressBookList;
    }

    /**
     * 获取默认地址簿
     * @return
     */
    @Override
    public AddressBook get_Default() {
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<AddressBook> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressBook::getUserId,userId);
        queryWrapper.eq(AddressBook::getIsDefault,1);
        AddressBook addressBook = this.getOne(queryWrapper);
        return addressBook;
    }

    /**
     * 更新默认地址簿
     * @param addressBook
     * @return
     */
    @Override
    public AddressBook update_Default(AddressBook addressBook) {
        LambdaUpdateWrapper<AddressBook> queryWrapper=new LambdaUpdateWrapper<>();
        queryWrapper.eq(AddressBook::getUserId,BaseContext.getCurrentId());
        queryWrapper.set(AddressBook::getIsDefault,0);
        this.update(queryWrapper);

        addressBook.setIsDefault(1);
        this.updateById(addressBook);
        return addressBook;
    }
}
